package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.FineTuningJob;
import com.micro.ai.models.service.FineTuningJobService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 微调任务控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/fine-tuning-jobs")
@Tag(name = "微调任务管理", description = "微调任务的增删改查、启动、取消")
public class FineTuningJobController {

    @Autowired
    private FineTuningJobService jobService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:job:create')")
    @Operation(summary = "创建微调任务", description = "创建新的微调训练任务")
    public ApiResponse<FineTuningJob> create(@Valid @RequestBody FineTuningJob job) {
        log.info("创建微调任务请求: tenantId={}, jobName={}", job.getTenantId(), job.getJobName());
        job.setCreatedBy(getCurrentUsername());
        FineTuningJob result = jobService.create(job);
        return ApiResponse.success("创建成功", result);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuning:job:view')")
    @Operation(summary = "获取任务详情", description = "获取微调任务详细信息")
    public ApiResponse<FineTuningJob> getById(
            @Parameter(description = "任务ID", required = true) @PathVariable String id) {
        log.info("查询微调任务详情: jobId={}", id);
        
        FineTuningJob job = jobService.getById(id);
        if (job == null) {
            return ApiResponse.error("404", "微调任务不存在");
        }
        
        return ApiResponse.success(job);
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuning:job:view')")
    @Operation(summary = "分页查询微调任务", description = "根据条件分页查询微调任务列表")
    public ApiResponse<Page<FineTuningJob>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        log.info("分页查询微调任务: pageNum={}, pageSize={}", pageNum, pageSize);
        
        Page<FineTuningJob> page = jobService.pageQuery(pageNum, pageSize, tenantId, keyword, status);
        return ApiResponse.success(page);
    }

    @PostMapping("/{id}/start")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:job:update')")
    @Operation(summary = "启动微调任务", description = "启动微调训练任务")
    public ApiResponse<Void> start(
            @Parameter(description = "任务ID", required = true) @PathVariable String id) {
        log.info("启动微调任务: jobId={}", id);
        
        jobService.start(id);
        return ApiResponse.successVoid("启动成功");
    }

    @PostMapping("/{id}/cancel")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:job:update')")
    @Operation(summary = "取消微调任务", description = "取消微调训练任务")
    public ApiResponse<Void> cancel(
            @Parameter(description = "任务ID", required = true) @PathVariable String id) {
        log.info("取消微调任务: jobId={}", id);
        
        jobService.cancel(id);
        return ApiResponse.successVoid("取消成功");
    }

    @GetMapping("/{id}/progress")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuning:job:view')")
    @Operation(summary = "获取任务进度", description = "获取微调任务的进度信息")
    public ApiResponse<FineTuningJob> getProgress(
            @Parameter(description = "任务ID", required = true) @PathVariable String id) {
        log.info("查询微调任务进度: jobId={}", id);
        
        FineTuningJob job = jobService.getProgress(id);
        return ApiResponse.success(job);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:job:update')")
    @Operation(summary = "更新微调任务", description = "更新微调任务信息")
    public ApiResponse<FineTuningJob> update(
            @Parameter(description = "任务ID", required = true) @PathVariable String id,
            @Valid @RequestBody FineTuningJob job) {
        log.info("更新微调任务请求: jobId={}", id);
        
        FineTuningJob result = jobService.update(id, job);
        return ApiResponse.success("更新成功", result);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuning:job:delete')")
    @Operation(summary = "删除微调任务", description = "删除微调任务")
    public ApiResponse<Void> delete(
            @Parameter(description = "任务ID", required = true) @PathVariable String id) {
        log.info("删除微调任务请求: jobId={}", id);
        
        jobService.delete(id);
        return ApiResponse.successVoid("删除成功");
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null ? authentication.getName() : "system";
    }
}

